package com.atguigu.gmall.product.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.common.cache.GmallCache;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.model.product.*;
import com.atguigu.gmall.product.mapper.*;
import com.atguigu.gmall.product.service.ManageService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;


import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class ManageServiceImpl implements ManageService {

    @Autowired
    private BaseAttrInfoMapper baseAttrInfoMapper;
    @Autowired
    private BaseAttrValueMapper baseAttrValueMapper;
    @Autowired
    private BaseCategory1Mapper baseCategory1Mapper;
    @Autowired
    private BaseCategory2Mapper baseCategory2Mapper;
    @Autowired
    private BaseCategory3Mapper baseCategory3Mapper;
    @Autowired
    private SpuInfoMapper spuInfoMapper;
    @Autowired
    private BaseSaleAttrMapper baseSaleAttrMapper;
    @Autowired
    private SpuImageMapper spuImageMapper;
    @Autowired
    private SpuSaleAttrMapper spuSaleAttrMapper;
    @Autowired
    private SpuSaleAttrValueMapper spuSaleAttrValueMapper;
    @Autowired
    private SkuInfoMapper skuInfoMapper;
    @Autowired
    private SkuImageMapper skuImageMapper;
    @Autowired
    private BaseCategoryViewMapper baseCategoryViewMapper;
    @Autowired
    private SkuSaleAttrValueMapper skuSaleAttrValueMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private BaseTrademarkMapper baseTrademarkMapper;



    @Override
    public IPage<SpuInfo> getSpuInfoList(Page<SpuInfo> spuInfoPage, SpuInfo spuInfo) {
        QueryWrapper<SpuInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("category3_id", spuInfo.getCategory3Id());
        queryWrapper.orderByAsc("id");
        IPage<SpuInfo> spuInfoIPage = spuInfoMapper.selectPage(spuInfoPage, queryWrapper);
        return spuInfoIPage;

    }

    @Override
    public List<BaseCategory1> getBaseCategory1() {
        //select * from base_category1
        return baseCategory1Mapper.selectList(null);
    }

    @Override
    public List<BaseCategory2> getBaseCategory2(Long category1Id) {
        //select * from base_category2 where category1_id=category1Id
        return baseCategory2Mapper.selectList(new QueryWrapper<BaseCategory2>().eq("category1_id", category1Id));
    }

    @Override
    public List<BaseCategory3> getBaseCategory3(Long category2Id) {
        return baseCategory3Mapper.selectList(new QueryWrapper<BaseCategory3>().eq("category2_id", category2Id));
    }

    @Override
    public List<BaseAttrInfo> getBaseAttrInfo(Long category1Id, Long category2Id, Long category3Id) {
        return baseAttrInfoMapper.selectBaseAttrInfoList(category1Id, category2Id, category3Id);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)//如果有异常会回滚
    public void saveAttrInfo(BaseAttrInfo baseAttrInfo) {
        if (baseAttrInfo.getId() != null) {
            baseAttrInfoMapper.updateById(baseAttrInfo);
        } else {
            baseAttrInfoMapper.insert(baseAttrInfo);
        }
        //先删除 ，后新增
        baseAttrValueMapper.delete(new QueryWrapper<BaseAttrValue>().eq("attr_id", baseAttrInfo.getId()));

        List<BaseAttrValue> attrValueList = baseAttrInfo.getAttrValueList();
        //判断list是否为空
        if (!CollectionUtils.isEmpty(attrValueList)) {
            for (BaseAttrValue baseAttrValue : attrValueList) {
                baseAttrValue.setAttrId(baseAttrInfo.getId());
                baseAttrValueMapper.insert(baseAttrValue);
            }
        }
    }

    @Override
    public List<BaseAttrValue> getAttrInfo(Long attrId) {
        return baseAttrValueMapper.selectList(new QueryWrapper<BaseAttrValue>().eq("attr_id", attrId));

    }

    @Override
    public BaseAttrInfo getBaseAttr(Long attrId) {
        BaseAttrInfo baseAttrInfo = baseAttrInfoMapper.selectById(attrId);
        if (baseAttrInfo != null) {
            List<BaseAttrValue> baseAttrValues = getAttrInfo(attrId);
            if (!CollectionUtils.isEmpty(baseAttrValues)) {
                baseAttrInfo.setAttrValueList(baseAttrValues);
            }
        }
        return baseAttrInfo;
    }

    @Override
    public List<BaseSaleAttr> getBaseSaleAttrList() {
        List<BaseSaleAttr> baseSaleAttrList = baseSaleAttrMapper.selectList(null);
        return baseSaleAttrList;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveSpuInfo(SpuInfo spuInfo) {
        spuInfoMapper.insert(spuInfo);
        List<SpuImage> spuImageList = spuInfo.getSpuImageList();
        if (!CollectionUtils.isEmpty(spuImageList)) {
            for (SpuImage spuImage : spuImageList) {
                spuImage.setId(spuInfo.getId());
                spuImageMapper.insert(spuImage);
            }
        }
        List<SpuSaleAttr> spuSaleAttrList = spuInfo.getSpuSaleAttrList();
        if (!CollectionUtils.isEmpty(spuSaleAttrList)) {
            for (SpuSaleAttr spuSaleAttr : spuSaleAttrList) {
                spuSaleAttr.setId(spuInfo.getId());
                spuSaleAttrMapper.insert(spuSaleAttr);
                List<SpuSaleAttrValue> spuSaleAttrValueList = spuSaleAttr.getSpuSaleAttrValueList();
                if (!CollectionUtils.isEmpty(spuSaleAttrValueList)) {
                    for (SpuSaleAttrValue spuSaleAttrValue : spuSaleAttrValueList) {
                        spuSaleAttrValue.setId(spuInfo.getId());
                        spuSaleAttrValue.setSaleAttrName(spuSaleAttr.getSaleAttrName());
                        spuSaleAttrValueMapper.insert(spuSaleAttrValue);
                    }
                }
            }

        }


    }

    @Override
    public List<SpuImage> getSpuImageList(Long spuId) {
        List<SpuImage> spuImages = spuImageMapper.selectList(new QueryWrapper<SpuImage>().eq("spu_id", spuId));
        return spuImages;
    }

    @Override
    public List<SpuSaleAttr> spuSaleAttrList(Long spuId) {
        List<SpuSaleAttr> spuSaleAttrs = spuSaleAttrMapper.spuSaleAttrList(spuId);
        return spuSaleAttrs;
    }

    @Override
    public void cancelSale(Long skuId) {

    }

    //使用redisson生成分布式锁
    private SkuInfo getSkuInfoRedisson(Long skuId) {
        //声明对象
        SkuInfo skuInfo = new SkuInfo();
        try {
            String skuKey = RedisConst.SKUKEY_PREFIX + skuId + RedisConst.SKUKEY_SUFFIX;
            //定义锁的key
            String skuLockKey = RedisConst.SKUKEY_PREFIX + skuId + RedisConst.SKULOCK_SUFFIX;
            skuInfo = (SkuInfo) redisTemplate.opsForValue().get(skuKey);
            String skuLockValue = UUID.randomUUID().toString();
            //缓存中没有数据
            if (skuInfo == null) {
                //拿到锁
                RLock lock = redissonClient.getLock(skuLockKey);
                //上锁
                boolean flag = false;
                try {
                    flag = lock.tryLock(RedisConst.SKULOCK_EXPIRE_PX1, RedisConst.SKULOCK_EXPIRE_PX1, TimeUnit.SECONDS);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if (flag) {
                    try {
                        SkuInfo skuInfoDB = getSkuInfoDB(skuId);
                        if (skuInfoDB == null) {
                            SkuInfo nullSkuInfo = new SkuInfo();
                            redisTemplate.opsForValue().set(skuKey, nullSkuInfo, RedisConst.SKUKEY_TEMPORARY_TIMEOUT, TimeUnit.SECONDS);
                            return nullSkuInfo;
                        }
                        redisTemplate.opsForValue().set(skuKey, skuInfoDB, RedisConst.SKUKEY_TIMEOUT, TimeUnit.SECONDS);
                        return skuInfo;
                    } finally {
                        lock.unlock();
                    }
                } else {
                    //没有拿到锁
                    try {
                        Thread.sleep(300);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    //自旋
                    return getSkuInfo(skuId);
                }
            } else {
                //缓存有数据
                return skuInfo;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return getSkuInfoDB(skuId);
    }


    @Override
    public SkuInfo getSkuInfo(Long skuId) {
        return getSkuInfoRedis(skuId);
    }

    //使用redis做分布式锁
    private SkuInfo getSkuInfoRedis(Long skuId) {
        SkuInfo skuInfo = new SkuInfo();
        try {
            String skuKey = RedisConst.SKUKEY_PREFIX + skuId + RedisConst.SKUKEY_SUFFIX;
            skuInfo = (SkuInfo) redisTemplate.opsForValue().get(skuKey);
            //防止击穿
            if (skuInfo == null) {
                //生成锁
                //定义一个锁的key
                String skuLockKey = RedisConst.SKUKEY_PREFIX + skuId + RedisConst.SKULOCK_SUFFIX;
                String skuLockValue = UUID.randomUUID().toString();
                //获取到锁
                Boolean lock = redisTemplate.opsForValue().setIfAbsent(skuLockKey, skuLockValue, RedisConst.SKULOCK_EXPIRE_PX1, TimeUnit.SECONDS);
                if (lock) {
                    //上锁成功
                    //查询数据库
                    //防止缓存穿透
                    SkuInfo skuInfoDB = getSkuInfoDB(skuId);
                    if (skuInfoDB == null) {
                        SkuInfo nullSkuInfo = new SkuInfo();
                        redisTemplate.opsForValue().set(skuKey, nullSkuInfo, RedisConst.SKUKEY_TEMPORARY_TIMEOUT, TimeUnit.SECONDS);
                        return nullSkuInfo;
                    } else {
                        redisTemplate.opsForValue().set(skuKey, skuInfoDB, RedisConst.SKUKEY_TIMEOUT, TimeUnit.SECONDS);
                        //释放锁
                        String scrip = "if redis.call('get',KEYS[1])==ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";
                        DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>(scrip);
                        redisTemplate.execute(redisScript, Arrays.asList(skuLockKey), skuLockValue);
                        return skuInfoDB;
                    }
                }
            } else {
                // 说明缓存中有数据
                return skuInfo;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //数据库暂时兜底
        return getSkuInfoDB(skuId);
    }

    /**
     * 数据库中查询数据
     *
     * @param skuId
     * @return
     */
    private SkuInfo getSkuInfoDB(Long skuId) {
        SkuInfo skuInfo = skuInfoMapper.selectById(skuId);
        skuInfo.setSkuImageList(skuImageMapper.selectList(new QueryWrapper<SkuImage>().eq("id", skuId)));
        return skuInfo;
    }

    @Override
    @GmallCache(prefix = "categoryViewByCategory3Id:")
    public BaseCategoryView getCategoryViewByCategory3Id(Long category3Id) {
        BaseCategoryView baseCategoryView = baseCategoryViewMapper.selectById(category3Id);
        return baseCategoryView;
    }

    @Override
    public BigDecimal getSkuPrice(Long SkuId) {
        SkuInfo skuInfo = skuInfoMapper.selectById(SkuId);
        if (skuInfo != null) {
            return skuInfo.getPrice();
        }
        //给默认值报错
        return new BigDecimal(0);
    }

    @Override
    public List<SpuSaleAttr> getSpuSaleAttrListCheckBySku(Long skuId, Long spuId) {
        return spuSaleAttrMapper.getSpuSaleAttrListCheckBySku(skuId, spuId);
    }

    @Override
    @GmallCache(prefix = "skuValueIds:")
    public Map getSkuValueIdsMap(Long spuId) {
        Map map = new HashMap();
        //执行sql语句获取sql结果集
        List<Map> mapList = skuSaleAttrValueMapper.selectSaleAttrValuesBySpu(spuId);
        if (!CollectionUtils.isEmpty(mapList)) {
            for (Map maps : mapList) {
                map.put(maps.get("value_ids"), maps.get("sku_id"));

            }
        }
        return map;
    }

    @Override
    public List<JSONObject> getBaseCategoryList() {
        int index = 1;
        //声明一个集合
        List<JSONObject> list = new ArrayList<>();
        //查询所有分类数据
        List<BaseCategoryView> baseCategoryViews = baseCategoryViewMapper.selectList(null);
        //key=category1Id value=List<BaseCategoryView>
        Map<Long, List<BaseCategoryView>> category1Map = baseCategoryViews.stream().collect(Collectors.groupingBy(BaseCategoryView::getCategory1Id));
        //循环遍历当前的数据合集
        Iterator<Map.Entry<Long, List<BaseCategoryView>>> iterator = category1Map.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<Long, List<BaseCategoryView>> next = iterator.next();
            Long category1Id = next.getKey();
            List<BaseCategoryView> category2List = next.getValue();

            String category1Name = category2List.get(0).getCategory1Name();
            //赋值
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("index", index);
            jsonObject.put("category1Id", category1Id);
            jsonObject.put("category1Name", category1Name);
            index++;

            Map<Long, List<BaseCategoryView>> category2Map = category2List.stream().collect(Collectors.groupingBy(BaseCategoryView::getCategory2Id));
            List<JSONObject> category2Child = new ArrayList<>();
            Iterator<Map.Entry<Long, List<BaseCategoryView>>> category2Iterator = category2Map.entrySet().iterator();
            while (category2Iterator.hasNext()) {
                Map.Entry<Long, List<BaseCategoryView>> category3List = category2Iterator.next();
                List<BaseCategoryView> category2Value = category3List.getValue();
                String category2Name = category2Value.get(0).getCategory2Name();
                Long category2Id = category3List.getKey();
                JSONObject category2Json = new JSONObject();
                category2Json.put("categoryName", category2Name);
                category2Json.put("categoryId", category2Id);
                //声明一个集合来存储所有的二级数据
                category2Child.add(category2Json);
                //声明一个三级分类集合数据
                List<JSONObject> category3Child =new ArrayList<>();
                //获取三级分类数据Id
                category2Value.forEach((baseCategoryView -> {
                    JSONObject category3=new JSONObject();
                    category3.put("categoryName",baseCategoryView.getCategory3Name());
                    category3.put("categoryId",baseCategoryView.getCategory3Id());
                    category3Child.add(category3);
                }));
                category2Json.put("categoryChild",category3Child);
            }

        }
        //返回集合数据
        return list;
    }

    @Override
    public BaseTrademark getTrademarkByTmId(Long tmId) {
        return baseTrademarkMapper.selectById(tmId);
    }

    @Override
    public List<BaseAttrInfo> getAttrList(Long skuId) {
        return baseAttrInfoMapper.selectBaseAttrInfoListBySkuId(skuId);
    }


}
